package gemini.castor.ui.client.page.content.account.mydownline.form;

import gemini.basic.model.Distributor;
import gemini.castor.ui.client.ServiceCatalog;
import gemini.castor.ui.client.mvp.callback.AbstractAsyncCallback;
import gemini.castor.ui.client.mvp.single.CastorWidgetDisplay;
import gemini.castor.ui.client.mvp.single.CastorWidgetPresenter;
import gemini.castor.ui.client.page.RootEvent;
import gemini.castor.ui.client.utils.PlaceConstants;
import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;

import com.google.inject.Inject;

public class MyDownlineFormPresenter extends
		CastorWidgetPresenter<MyDownlineFormPresenter.Display> {

	@Inject
	public MyDownlineFormPresenter(Display display, EventBus globalEventBus) {
		super(display, globalEventBus);
	}

	public interface Display extends CastorWidgetDisplay {
		void setModel(MyDownlineInfoFormModel downlineList);

	}

	public static final Place PLACE = new Place(
			PlaceConstants.PLACE_MY_DOWNLINE);

	private String distributorCode;

	@Override
	public void setInputObject(Object ob) {
		distributorCode = (String) ob;
	}

	@Override
	protected void onBind() {
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getDownlineService().fetchDownlineByCode(
				distributorCode, new AbstractAsyncCallback<Distributor>() {

					@Override
					public void onSuccess(Distributor result) {
						eventBus.fireEvent(new RootEvent(
								RootEvent.ForwardType.UN_MASK));
						display.setModel(createModelFromDistributor(result));
						display.loadData();
					}
				});
	}

	protected MyDownlineInfoFormModel createModelFromDistributor(
			Distributor distributor) {
		MyDownlineInfoFormModel distributorModel = new MyDownlineInfoFormModel();
		distributorModel.setDistributors(distributor.getDistributors());
		return distributorModel;
	}

	@Override
	public Place getPlace() {
		return PLACE;
	}
}
